package com.lucy.disk.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.SecureUtil;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.common.exception.BusinessException;
import com.lucy.disk.domain.entity.FileEntity;
import com.lucy.disk.loader.StorageServiceLoader;
import com.lucy.disk.params.FileUploadParams;
import com.lucy.disk.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Optional;


/**
 * @author kindear
 * 文件传输控制器
 */
@Slf4j
@RestController
@RequestMapping("disk")
@Api(tags = "文件传输")
public class DiskTransferController {
    @Autowired
    FileService fileService;

    @Autowired
    StorageServiceLoader storageService;

    @PostMapping("upload")
    @ApiOperation(value = "文件上传")
    public ResponseDTO<Object> fileUpload(@Validated FileUploadParams params) throws Exception {

        // 如果文件为空
        if (Validator.isEmpty(params.getFile())){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"上传文件不可为空");
        }
        String fileName = params.getFileName();
        // 如果文件名为空 -- 获取原始文件名
        if (Validator.isEmpty(fileName)){
            fileName = params.getFile().getOriginalFilename();
        }
        // 简单初始化
        FileEntity fileEntity = new FileEntity(fileName);
        // 设置文件父目录
        String dirId = "";
        if (Validator.isNotEmpty(params.getDirId())){
            dirId = params.getDirId();
        }
        fileEntity.setDirId(dirId);
        // 获取当前登录用户
        String loginId = StpUtil.getLoginIdAsString();
        fileEntity.setUserId(loginId);
        // 设置为非目录
        fileEntity.setIsDir(0);
        // 计算md5 和 文件大小
        fileEntity.setFileSize(params.getFile().getSize());
        fileEntity.setMd5(SecureUtil.md5(params.getFile().getInputStream()));
        // 计算拓展名
        String extName = FileNameUtil.extName(fileName);
        FileEntity saveRes = fileService.saveOne(fileEntity);
        String ossUrl = saveRes.getId() +"." + extName;
        // 设置映射地址
        saveRes.setOssUrl(ossUrl);
        // 计算 文件拓展信息
//        saveRes.setFileExtend(null);
        // 不异步执行
        storageService.uploadFile(params.getFile(),ossUrl);
        return ResponseDTO.succData(
                fileService.updateOne(saveRes)
        );
    }

    @GetMapping("download/{fileId}")
    @ApiOperation(value = "文件下载",notes = "")
    public ResponseEntity<byte[]> downLoadById(@PathVariable("fileId") String fileId, HttpServletRequest request) throws Exception {
        Optional<FileEntity> fileOp = fileService.getOne(fileId);
        if (!fileOp.isPresent()){
            throw new BusinessException(HttpStatus.NOT_FOUND);
        }
        FileEntity fileEntity = fileOp.get();

        String ossUrl = fileEntity.getOssUrl();

        InputStream stream = storageService.downloadFile(ossUrl);

        return fileService.downloadMethod(stream,request,fileEntity);
    }




}
